import os
from flask import (
    render_template,
    request,
    Response,
    flash,
    redirect,
    url_for,
    jsonify,
    g,
    send_from_directory,
    Blueprint,
)
from flask_login import login_required, current_user
import json
import uuid
import xml.etree.ElementTree as ET

bp_tool = Blueprint("bp_tool", __name__)

BASE_DIR = os.path.dirname(__file__)
TMP = os.path.join(BASE_DIR, "task", "tmp")

template = """
<exchange xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://download.autodesk.com/us/navisworks/schemas/nw-exchange-12.0.xsd" units="m">
  <selectionsets>
  </selectionsets>
</exchange>
"""


def new_viewfolder(name):
    """
    create a viewfolder node
    """
    viewfolder = ET.Element(
        "viewfolder", attrib={"guid": str(uuid.uuid1()), "name": name}
    )
    return viewfolder


def new_selectionset(display_name, attr_name, attr_value):
    """
    create a selectionset node
    """
    selectionset = ET.Element(
        "selectionset", attrib={"guid": str(uuid.uuid1()), "name": display_name}
    )
    findspec = ET.SubElement(
        selectionset, "findspec", attrib={"disjoint": "0", "mode": "all"}
    )
    conditions = ET.SubElement(findspec, "conditions")
    condition = ET.SubElement(
        conditions, "condition", attrib={"flags": "10", "test": "equals"}
    )

    category = ET.SubElement(condition, "category")
    category_name = ET.SubElement(
        category, "name", attrib={"internal": "lcldrvm_props"}
    )
    category_name.text = "PDMS"

    _property = ET.SubElement(condition, "property")
    property_name = ET.SubElement(
        _property,
        "name",
        attrib={"internal": "lcldrvm_prop_{0}".format(attr_name.lower())},
    )
    property_name.text = attr_name

    value = ET.SubElement(condition, "value")

    try:
        int(attr_value)
        name_type = "int32"
    except:
        name_type = "wstring"

    value_data = ET.SubElement(value, "data", attrib={"type": name_type})
    value_data.text = attr_value

    locator = ET.SubElement(findspec, "locator")
    locator.text = "/"

    return selectionset


@bp_tool.route("/", methods=["GET"])
def index():
    return render_template("tool/index.html")

    # return redirect(url_for('bp_partner.send', user_id=current_user.id), code=302)


@bp_tool.route("/nwss", methods=["GET", "POST"])
def navisworks_search_sets():
    if request.method == "GET":
        return render_template("tool/nwss.html")
    else:
        data = request.get_json()
        if data:
            tree = ET.ElementTree(ET.fromstring(template))
            selectionsets = tree.find("selectionsets")

            for row in data:
                dir = row["text"]
                folder = new_viewfolder(dir)
                selectionsets.append(folder)
                nodes = row["nodes"]
                for node in nodes:
                    attr_name = node["type"]
                    attr_value = node["value"]
                    display_name = node["text"].split("(属性名")[0]
                    folder.append(new_selectionset(display_name, attr_name, attr_value))

            file_name = uuid.uuid4().hex
            fp = os.path.join(TMP, file_name)
            tree.write(
                fp,
                encoding="UTF-8",
                xml_declaration=True,
                default_namespace=None,
                method="xml",
            )

            return jsonify({"filename": file_name})
        else:
            return jsonify({"filename": ""})


@bp_tool.route("/download")
def download():
    file_name = request.args.get("fp")
    d = send_from_directory(directory=TMP, filename=file_name)
    filenames = {"filename": "DDD.xml"}
    d.headers.set("Content-Disposition", "attachment", **filenames)
    return d


@bp_tool.route("/todo", methods=["GET"])
def todo():
    return render_template("tool/todo.html")


if __name__ == "__main__":
    pass
